﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using Sparklings.JsonUtils;
using Sparklings.RayTracing;
using Sparklings.Rendering;
using System.Linq;

namespace Sparklings.LevelElements
{
    public class ExitPoint : Tile
    {
        public ExitPoint(Level l, int x, int y, RayColor color)
            : base(l, x, y, false)
        {
            Color = color;
        }
        public override void LoadGraphicsRelatedElements()
        {
            base.LoadGraphicsRelatedElements();
            BaseTexture = Level.ContentManager.Load<Texture2D>("exitpoint");
            portalTexture = Level.ContentManager.Load<Texture2D>("exitpoint_portal");
        }
        public override void DrawBase(RenderContext rc)
        {
            base.DrawBase(rc);
            rc.Draw(portalTexture, Center, Color.ToColor());
        }
        public override void Update(GameTime gameTime)
        {
            var sparklingsToRemove = GetCurrentlyContainedSparklings().Where(x => x.Color.Contains(Color));
            foreach (var s in GetCurrentlyContainedSparklings().Where(x => x.Color.Contains(Color)&&!x.Disappearing))
            {
                s.MakeDisappear();
                --Level.SparklingsNeeded;
            }
        }

        public override JToken GetJsonData(JsonOverrider converter)
        {
            var tok = new JObject();
            tok["color"] = converter.Write(Color);
            return tok;
        }

        public static object ConstructFromData(JsonOverrider converter, JToken toConvert, Level level, int x, int y)
        {
            return new ExitPoint(level, x, y, converter.Read<RayColor>(toConvert["color"]));
        }
        
        public override bool IsPassableBySparkling(Sparkling c) { return true; }
        public RayColor Color { get; set; }
        protected Texture2D portalTexture;
    }
}
